<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form inline>
      <el-form-item label="表单名称">
        <el-input clearable placeholder="请输入表单名称" v-model="searchForm.formName" style="width: 200px" />
      </el-form-item>
      <el-form-item label="表单状态">
        <el-select v-model="searchForm.isActive" placeholder="请选择表单状态" clearable style="width: 150px">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" size="small">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset" size="small">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="handleAdd" size="small">
          <el-icon><Plus /></el-icon>
          新增表单
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <BaseTable
      :table-data="formTemplateList"
      :table-columns="tableColumns"
      :table-loading="loading"
      :page-num="pageInfo.pageNum"
      :page-size="pageInfo.pageSize"
      :total="pageInfo.total"
      :options="tableOptions"
      @update:pageNum="pageInfo.pageNum = $event"
      @update:pageSize="pageInfo.pageSize = $event"
      @turnOn="loadFormTemplateList"
    >
      <!-- 表单状态插槽 -->
      <template #isActive="{ row }">
        <el-tag :type="row.isActive ? 'success' : 'danger'">
          {{ row.isActive ? "启用" : "禁用" }}
        </el-tag>
      </template>

      <!-- 字段数量插槽 -->
      <template #fieldCount="{ row }">
        <el-tag type="info"> {{ row.fields ? row.fields.length : 0 }} 个字段 </el-tag>
      </template>

      <!-- 创建时间插槽 -->
      <template #createdAt="{ row }">
        <span v-if="row.createdAt">
          {{ formatDate(row.createdAt) }}
        </span>
        <span v-else>--</span>
      </template>

      <!-- 操作插槽 -->
      <template #operation="{ row }">
        <el-button size="small" type="primary" text @click="handleView(row)"> 查看 </el-button>
        <el-button size="small" type="primary" text @click="handleEdit(row)"> 编辑 </el-button>
        <el-button size="small" type="danger" text @click="handleDelete(row)"> 删除 </el-button>
      </template>
    </BaseTable>

    <!-- 表单详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? `编辑表单模板 - ${currentFormTemplate?.formName}` : `查看表单模板 - ${currentFormTemplate?.formName}`"
      width="80%"
      :before-close="handleCloseDialog"
      destroy-on-close
    >
      <div v-if="currentFormTemplate">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="表单名称">
            {{ currentFormTemplate.formName }}
          </el-descriptions-item>
          <el-descriptions-item label="表单标识">
            {{ currentFormTemplate.formKey }}
          </el-descriptions-item>
          <el-descriptions-item label="表单描述">
            {{ currentFormTemplate.formDescription || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentFormTemplate.isActive ? 'success' : 'danger'">
              {{ currentFormTemplate.isActive ? "启用" : "禁用" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ currentFormTemplate.createdBy }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentFormTemplate.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 字段列表 -->
        <div style="margin-top: 20px;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h3 style="margin: 0;">字段列表 ({{ currentFormTemplate.fields?.length || 0 }}个字段)</h3>
            <el-button
              v-if="isEditMode"
              type="primary"
              size="small"
              @click="handleAddFieldToTemplate"
            >
              <el-icon><Plus /></el-icon>
              添加字段
            </el-button>
          </div>

          <el-table :data="currentFormTemplate.fields" border style="width: 100%">
            <el-table-column prop="fieldName" label="字段名称" width="120" />
            <el-table-column prop="fieldLabel" label="字段标签" width="120" />
            <el-table-column prop="fieldType" label="字段类型" width="100">
              <template #default="{ row }">
                {{ getFieldTypeLabel(row.fieldType) }}
              </template>
            </el-table-column>
            <el-table-column prop="required" label="是否必填" width="100">
              <template #default="{ row }">
                <el-tag :type="row.required ? 'danger' : 'info'">
                  {{ row.required ? "必填" : "选填" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="fieldDescription" label="字段描述" show-overflow-tooltip />
            <el-table-column prop="sortOrder" label="排序" width="80" />
            <el-table-column v-if="isEditMode" label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  size="small"
                  text
                  @click="handleRemoveFieldFromTemplate(row.fieldName)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="handleCloseDialog">
            {{ isEditMode ? '取消' : '关闭' }}
          </el-button>
          <el-button v-if="isEditMode" type="primary" @click="handleSaveTemplate">
            保存修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增表单弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增表单模板" width="60%" :before-close="handleCloseAddDialog" destroy-on-close>
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px" style="max-width: 100%">
        <!-- 基本信息 -->
        <div style="margin-bottom: 20px">
          <h4 style="margin-bottom: 15px; color: #409eff">基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="表单名称" prop="formName">
                <el-input v-model="addForm.formName" placeholder="请输入表单名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表单标识" prop="formKey">
                <el-input v-model="addForm.formKey" placeholder="请输入表单标识，如：user-feedback-form" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="表单描述" prop="formDescription">
                <el-input v-model="addForm.formDescription" type="textarea" :rows="3" placeholder="请输入表单描述" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-switch v-model="addForm.isActive" active-text="启用" inactive-text="禁用" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 字段管理 -->
        <div>
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px">
            <h4 style="margin: 0; color: #409eff">表单字段</h4>
            <el-button type="primary" size="small" @click="handleAddField">
              <el-icon><Plus /></el-icon>
              添加字段
            </el-button>
          </div>

          <!-- 字段列表 -->
          <div v-if="addForm.fields.length === 0" style="text-align: center; padding: 40px; color: #999">暂无字段，请点击"添加字段"按钮添加表单字段</div>

          <div v-else>
            <el-card v-for="(field, index) in addForm.fields" :key="index" style="margin-bottom: 15px" shadow="hover">
              <template #header>
                <div style="display: flex; justify-content: space-between; align-items: center">
                  <span>字段 {{ index + 1 }}: {{ field.fieldLabel || "未命名字段" }}</span>
                  <div>
                    <el-button size="small" type="primary" text @click="handleEditField(index)"> 编辑 </el-button>
                    <el-button size="small" type="danger" text @click="handleRemoveField(index)"> 删除 </el-button>
                  </div>
                </div>
              </template>

              <el-descriptions :column="3" size="small">
                <el-descriptions-item label="字段名称">
                  {{ field.fieldName }}
                </el-descriptions-item>
                <el-descriptions-item label="字段标签">
                  {{ field.fieldLabel }}
                </el-descriptions-item>
                <el-descriptions-item label="字段类型">
                  {{ getFieldTypeLabel(field.fieldType) }}
                </el-descriptions-item>
                <el-descriptions-item label="是否必填">
                  <el-tag :type="field.required ? 'danger' : 'info'" size="small">
                    {{ field.required ? "必填" : "选填" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="排序">
                  {{ field.sortOrder }}
                </el-descriptions-item>
                <el-descriptions-item label="默认值">
                  {{ field.defaultValue || "--" }}
                </el-descriptions-item>
                <el-descriptions-item label="字段描述" :span="3">
                  {{ field.fieldDescription || "--" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="field.options && field.options.length > 0" label="选项" :span="3">
                  <el-tag v-for="option in field.options" :key="option" size="small" style="margin-right: 5px">
                    {{ option }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitAdd"> 确定创建 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 字段编辑弹窗 -->
    <el-dialog v-model="fieldDialogVisible" :title="currentFieldIndex === -1 ? '添加字段' : '编辑字段'" width="70%" :before-close="handleCloseFieldDialog" destroy-on-close>
      <el-form ref="fieldFormRef" :model="fieldForm" :rules="fieldFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称，如：userName" clearable />
              <div style="font-size: 12px; color: #999; margin-top: 4px">用于数据存储的字段名，必须以字母开头</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段标签" prop="fieldLabel">
              <el-input v-model="fieldForm.fieldLabel" placeholder="请输入字段标签，如：姓名" clearable />
              <div style="font-size: 12px; color: #999; margin-top: 4px">显示给用户看的字段名称</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型" style="width: 100%">
                <el-option v-for="option in fieldTypeOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否必填">
              <el-switch v-model="fieldForm.required" active-text="必填" inactive-text="选填" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="fieldForm.sortOrder" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="字段描述">
          <el-input v-model="fieldForm.fieldDescription" type="textarea" :rows="2" placeholder="请输入字段描述（可选）" clearable />
        </el-form-item>

        <el-form-item label="默认值">
          <el-input v-model="fieldForm.defaultValue" placeholder="请输入默认值（可选）" clearable />
        </el-form-item>

        <!-- 选项配置（仅在select、radio、checkbox类型时显示） -->
        <div v-if="['select', 'radio', 'checkbox'].includes(fieldForm.fieldType)">
          <el-form-item label="选项配置">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px; padding: 15px">
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px">
                <span style="font-weight: bold">选项列表</span>
                <el-button size="small" type="primary" @click="handleAddOption">
                  <el-icon><Plus /></el-icon>
                  添加选项
                </el-button>
              </div>

              <div v-if="fieldForm.options.length === 0" style="text-align: center; color: #999; padding: 20px">暂无选项，请点击"添加选项"按钮添加</div>

              <div v-else>
                <div v-for="(option, index) in fieldForm.options" :key="index" style="display: flex; align-items: center; margin-bottom: 8px">
                  <el-input v-model="fieldForm.options[index]" placeholder="请输入选项内容" style="flex: 1; margin-right: 10px" />
                  <el-button size="small" type="danger" text @click="handleRemoveOption(index)"> 删除 </el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 验证规则配置 -->
        <el-form-item label="验证规则">
          <el-input v-model="fieldForm.validationRule" placeholder="请输入正则表达式验证规则（可选）" clearable />
          <div style="font-size: 12px; color: #999; margin-top: 4px">例如：^[\\u4e00-\\u9fa5a-zA-Z]{2,20}$ （2-20个中英文字符）</div>
        </el-form-item>

        <el-form-item label="验证提示">
          <el-input v-model="fieldForm.validationMessage" placeholder="请输入验证失败时的提示信息（可选）" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="handleCloseFieldDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitField">
            {{ currentFieldIndex === -1 ? "添加字段" : "保存修改" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import BaseTable from "@/components/BaseTable/index.vue";
import { getFormTemplateList, getFormTemplateById, deleteFormTemplate, createFormTemplate, addFieldToTemplate, removeFieldFromTemplate } from "@/api/extend";
import dayjs from "dayjs";

// 表单模板数据类型定义
interface FormField {
  fieldName: string;
  fieldLabel: string;
  fieldDescription?: string;
  fieldType: string;
  required: boolean;
  defaultValue?: string;
  sortOrder: number;
  validationRule?: string;
  validationMessage?: string;
  options?: string[];
}

interface FormTemplate {
  _id: string;
  formName: string;
  formDescription?: string;
  formKey: string;
  isActive: boolean;
  createdBy?: string;
  fields?: FormField[];
  createdAt?: Date;
  updatedAt?: Date;
}

// 查询表单
const searchForm = reactive({
  formName: "",
  isActive: undefined as boolean | undefined
});

// 分页信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});

// 表单模板数据
const formTemplateList = ref<FormTemplate[]>([]);
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const currentFormTemplate = ref<FormTemplate | null>(null);
const isEditMode = ref(false); // 标识是否为编辑模式

// 新增表单弹窗相关
const addDialogVisible = ref(false);
const addFormRef = ref();
const addForm = ref({
  formName: "",
  formDescription: "",
  formKey: "",
  isActive: true,
  createdBy: "admin",
  fields: [] as FormField[]
});

// 字段编辑弹窗相关
const fieldDialogVisible = ref(false);
const fieldFormRef = ref();
const currentFieldIndex = ref(-1);
const fieldForm = ref({
  fieldName: "",
  fieldLabel: "",
  fieldDescription: "",
  fieldType: "text",
  required: false,
  defaultValue: "",
  sortOrder: 1,
  validationRule: "",
  validationMessage: "",
  options: [] as string[]
});

// 字段类型选项
const fieldTypeOptions = [
  { label: "单行文本", value: "text" },
  { label: "邮箱", value: "email" },
  { label: "多行文本", value: "textarea" },
  { label: "下拉选择", value: "select" },
  { label: "单选框", value: "radio" },
  { label: "多选框", value: "checkbox" }
];

// 新增表单验证规则
const addFormRules = {
  formName: [
    { required: true, message: "请输入表单名称", trigger: "blur" },
    { min: 2, max: 50, message: "表单名称长度应为2-50个字符", trigger: "blur" }
  ],
  formKey: [
    { required: true, message: "请输入表单标识", trigger: "blur" },
    { pattern: /^[a-zA-Z][a-zA-Z0-9-_]*$/, message: "表单标识必须以字母开头，只能包含字母、数字、横线和下划线", trigger: "blur" }
  ],
  formDescription: [{ max: 200, message: "表单描述不能超过200个字符", trigger: "blur" }]
};

// 字段表单验证规则
const fieldFormRules = {
  fieldName: [
    { required: true, message: "请输入字段名称", trigger: "blur" },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: "字段名称必须以字母开头，只能包含字母、数字和下划线", trigger: "blur" },
    { min: 2, max: 50, message: "字段名称长度应为2-50个字符", trigger: "blur" }
  ],
  fieldLabel: [
    { required: true, message: "请输入字段标签", trigger: "blur" },
    { min: 1, max: 50, message: "字段标签长度应为1-50个字符", trigger: "blur" }
  ],
  fieldType: [{ required: true, message: "请选择字段类型", trigger: "change" }],
  sortOrder: [
    { required: true, message: "请输入排序值", trigger: "blur" },
    { type: "number", min: 1, max: 999, message: "排序值应为1-999的数字", trigger: "blur" }
  ],
  validationRule: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value && value.trim() !== "") {
          try {
            new RegExp(value);
            callback();
          } catch (error) {
            callback(new Error("请输入有效的正则表达式"));
          }
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 表格配置
const tableOptions = {
  stripe: true,
  showSelect: false,
  showOrder: true,
  showOption: true,
  optionWidth: 200
};

// 表格列配置
const tableColumns = [
  {
    prop: "formName",
    label: "表单名称",
    width: 180
  },
  {
    prop: "formKey",
    label: "表单标识",
    width: 200,
    showOverflowTooltip: true
  },
  {
    prop: "formDescription",
    label: "表单描述",
    width: 250,
    showOverflowTooltip: true
  },
  {
    prop: "isActive",
    label: "状态",
    width: 100,
    slotable: true
  },
  {
    prop: "fieldCount",
    label: "字段数量",
    width: 120,
    slotable: true
  },
  {
    prop: "createdBy",
    label: "创建者",
    width: 120
  },
  {
    prop: "createdAt",
    label: "创建时间",
    width: 180,
    slotable: true
  }
];

/**
 * 获取字段类型标签
 * @param fieldType 字段类型
 */
const getFieldTypeLabel = (fieldType: string): string => {
  const option = fieldTypeOptions.find((opt) => opt.value === fieldType);
  return option ? option.label : fieldType;
};

/**
 * 格式化日期
 * @param date 日期
 */
const formatDate = (date: Date | string | undefined): string => {
  if (!date) return "--";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

/**
 * 分页查询表单模板列表
 */
const loadFormTemplateList = async () => {
  try {
    loading.value = true;
    const params = {
      page: pageInfo.pageNum,
      limit: pageInfo.pageSize,
      isActive: searchForm.isActive
    };

    const res = await getFormTemplateList(params);
    console.log(res, "res");

    if (res.data) {
      formTemplateList.value = res.data.data;
      pageInfo.total = res.data.total;
    }
    console.log("表单模板列表:", res.data);
  } catch (error) {
    console.error("获取表单模板列表失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索处理
 */
const handleSearch = () => {
  pageInfo.pageNum = 1;
  loadFormTemplateList();
};

/**
 * 重置处理
 */
const handleReset = () => {
  searchForm.formName = "";
  searchForm.isActive = undefined;
  pageInfo.pageNum = 1;
  loadFormTemplateList();
};

/**
 * 新增处理
 */
const handleAdd = () => {
  // 重置表单数据
  addForm.value = {
    formName: "",
    formDescription: "",
    formKey: "",
    isActive: true,
    createdBy: "admin",
    fields: []
  };
  addDialogVisible.value = true;
};

/**
 * 查看处理
 * @param row 行数据
 */
const handleView = async (row: FormTemplate) => {
  try {
    const res = await getFormTemplateById(row._id);
    if (res.data) {
      currentFormTemplate.value = res.data as FormTemplate;
      dialogTitle.value = `查看表单模板 - ${row.formName}`;
      isEditMode.value = false;
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error("获取表单模板详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

/**
 * 编辑处理
 * @param row 行数据
 */
const handleEdit = async (row: FormTemplate) => {
  try {
    const res = await getFormTemplateById(row._id);
    if (res.data) {
      currentFormTemplate.value = res.data as FormTemplate;
      dialogTitle.value = `编辑表单模板 - ${row.formName}`;
      isEditMode.value = true;
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error("获取表单模板详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

/**
 * 删除处理
 * @param row 行数据
 */
const handleDelete = (row: FormTemplate) => {
  ElMessageBox.confirm(`确定要删除表单模板 "${row.formName}" 吗？`, "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteFormTemplate(row._id);
        ElMessage.success("删除成功");
        loadFormTemplateList();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/**
 * 关闭弹窗处理
 */
const handleCloseDialog = () => {
  dialogVisible.value = false;
  currentFormTemplate.value = null;
  isEditMode.value = false;
};

/**
 * 添加字段到模板
 */
const handleAddFieldToTemplate = () => {
  if (!currentFormTemplate.value) return;

  // 重置字段表单
  fieldForm.value = {
    fieldName: "",
    fieldLabel: "",
    fieldDescription: "",
    fieldType: "text",
    required: false,
    defaultValue: "",
    sortOrder: (currentFormTemplate.value.fields?.length || 0) + 1,
    validationRule: "",
    validationMessage: "",
    options: []
  };
  currentFieldIndex.value = -1;
  fieldDialogVisible.value = true;
};

/**
 * 从模板中删除字段
 * @param fieldName 字段名称
 */
const handleRemoveFieldFromTemplate = async (fieldName: string) => {
  if (!currentFormTemplate.value) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除字段 "${fieldName}" 吗？删除后不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用API删除字段
    await removeFieldFromTemplate(currentFormTemplate.value._id, fieldName);

    // 从本地数据中移除字段
    if (currentFormTemplate.value.fields) {
      currentFormTemplate.value.fields = currentFormTemplate.value.fields.filter(
        field => field.fieldName !== fieldName
      );
    }

    ElMessage.success('字段删除成功');
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除字段失败:', error);
      ElMessage.error(error.message || '删除字段失败');
    }
  }
};

/**
 * 保存模板修改
 */
const handleSaveTemplate = () => {
  ElMessage.success('模板修改已保存');
  handleCloseDialog();
  loadFormTemplateList(); // 刷新列表
};

/**
 * 关闭新增弹窗处理
 */
const handleCloseAddDialog = () => {
  addDialogVisible.value = false;
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};

/**
 * 提交新增表单
 */
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return;

  try {
    // 验证基本表单信息
    await addFormRef.value.validate();

    // 验证字段数量
    if (addForm.value.fields.length === 0) {
      ElMessage.warning("请至少添加一个字段");
      return;
    }

    // 验证字段完整性
    const invalidFields = addForm.value.fields.filter((field) => {
      // 检查必填字段
      if (!field.fieldName || !field.fieldLabel || !field.fieldType) {
        return true;
      }

      // 检查需要选项的字段类型是否有选项
      if (["select", "radio", "checkbox"].includes(field.fieldType)) {
        if (!field.options || field.options.length === 0) {
          return true;
        }
      }

      // 检查验证规则格式
      if (field.validationRule) {
        try {
          new RegExp(field.validationRule);
        } catch (error) {
          return true;
        }
      }

      return false;
    });

    if (invalidFields.length > 0) {
      ElMessage.warning("存在不完整的字段配置，请检查所有字段信息");
      return;
    }

    // 检查字段名称唯一性
    const fieldNames = addForm.value.fields.map((field) => field.fieldName);
    const uniqueFieldNames = [...new Set(fieldNames)];
    if (fieldNames.length !== uniqueFieldNames.length) {
      ElMessage.warning("存在重复的字段名称，请检查字段配置");
      return;
    }

    // 检查排序值唯一性
    const sortOrders = addForm.value.fields.map((field) => field.sortOrder);
    const uniqueSortOrders = [...new Set(sortOrders)];
    if (sortOrders.length !== uniqueSortOrders.length) {
      ElMessage.warning("存在重复的排序值，请检查字段配置");
      return;
    }

    // 准备提交数据
    const submitData = {
      ...addForm.value,
      fields: addForm.value.fields.sort((a, b) => a.sortOrder - b.sortOrder)
    };

    // 调用API创建表单模板
    await createFormTemplate(submitData);

    ElMessage.success("表单模板创建成功");
    handleCloseAddDialog();
    await loadFormTemplateList();
  } catch (error: any) {
    console.error("创建表单模板失败:", error);
    ElMessage.error(error.message || "创建表单模板失败，请重试");
  }
};

/**
 * 添加选项（用于select、radio、checkbox类型字段）
 */
const handleAddOption = () => {
  fieldForm.value.options.push("");
};

/**
 * 删除选项
 * @param index 选项索引
 */
const handleRemoveOption = (index: number) => {
  fieldForm.value.options.splice(index, 1);
};

/**
 * 添加字段处理
 */
const handleAddField = () => {
  // 重置字段表单
  fieldForm.value = {
    fieldName: "",
    fieldLabel: "",
    fieldDescription: "",
    fieldType: "text",
    required: false,
    defaultValue: "",
    sortOrder: addForm.value.fields.length + 1,
    validationRule: "",
    validationMessage: "",
    options: []
  };
  currentFieldIndex.value = -1;
  fieldDialogVisible.value = true;
};

/**
 * 编辑字段处理
 * @param index 字段索引
 */
const handleEditField = (index: number) => {
  const field = addForm.value.fields[index];
  fieldForm.value = { ...field };
  currentFieldIndex.value = index;
  fieldDialogVisible.value = true;
};

/**
 * 删除字段处理
 * @param index 字段索引
 */
const handleRemoveField = (index: number) => {
  ElMessageBox.confirm("确定要删除这个字段吗？", "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      addForm.value.fields.splice(index, 1);
      // 重新排序
      addForm.value.fields.forEach((field, idx) => {
        field.sortOrder = idx + 1;
      });
      ElMessage.success("删除字段成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/**
 * 关闭字段弹窗处理
 */
const handleCloseFieldDialog = () => {
  fieldDialogVisible.value = false;
  if (fieldFormRef.value) {
    fieldFormRef.value.resetFields();
  }
};

/**
 * 提交字段表单（新增或编辑字段）
 */
const handleSubmitField = async () => {
  if (!fieldFormRef.value) return;

  try {
    await fieldFormRef.value.validate();

    // 验证选项配置（对于需要选项的字段类型）
    if (["select", "radio", "checkbox"].includes(fieldForm.value.fieldType)) {
      const validOptions = fieldForm.value.options.filter((option) => option.trim() !== "");
      if (validOptions.length === 0) {
        ElMessage.warning("请至少添加一个选项");
        return;
      }
      fieldForm.value.options = validOptions;
    } else {
      // 清空不需要选项的字段类型的选项数据
      fieldForm.value.options = [];
    }

    // 创建字段对象
    const fieldData: FormField = {
      fieldName: fieldForm.value.fieldName,
      fieldLabel: fieldForm.value.fieldLabel,
      fieldDescription: fieldForm.value.fieldDescription,
      fieldType: fieldForm.value.fieldType,
      required: fieldForm.value.required,
      defaultValue: fieldForm.value.defaultValue,
      sortOrder: fieldForm.value.sortOrder,
      validationRule: fieldForm.value.validationRule,
      validationMessage: fieldForm.value.validationMessage,
      ...(fieldForm.value.options.length > 0 && { options: fieldForm.value.options })
    };

    if (currentFieldIndex.value === -1) {
      // 新增字段到模板
      if (currentFormTemplate.value && isEditMode.value) {
        // 检查字段名称是否重复
        const existingField = currentFormTemplate.value.fields?.find(
          field => field.fieldName === fieldForm.value.fieldName
        );
        if (existingField) {
          ElMessage.warning('字段名称已存在，请使用其他名称');
          return;
        }

        // 调用API添加字段到模板
         await addFieldToTemplate({
           formTemplateId: currentFormTemplate.value._id,
           field: fieldData
         });

        // 更新本地数据
        if (!currentFormTemplate.value.fields) {
          currentFormTemplate.value.fields = [];
        }
        currentFormTemplate.value.fields.push(fieldData);
        currentFormTemplate.value.fields.sort((a, b) => a.sortOrder - b.sortOrder);

        ElMessage.success('字段添加成功');
      } else {
        // 新增表单模式
        // 检查字段名称是否重复
        const existingField = addForm.value.fields.find(
          field => field.fieldName === fieldForm.value.fieldName
        );
        if (existingField) {
          ElMessage.warning('字段名称已存在，请使用其他名称');
          return;
        }

        addForm.value.fields.push(fieldData);
        addForm.value.fields.sort((a, b) => a.sortOrder - b.sortOrder);
        ElMessage.success('字段添加成功');
      }
    } else {
      // 编辑字段
      if (currentFormTemplate.value && isEditMode.value) {
        // 检查字段名称是否重复（排除当前编辑的字段）
        const existingField = currentFormTemplate.value.fields?.find((field, index) =>
          field.fieldName === fieldForm.value.fieldName && index !== currentFieldIndex.value
        );
        if (existingField) {
          ElMessage.warning('字段名称已存在，请使用其他名称');
          return;
        }

        // 更新本地数据
        if (currentFormTemplate.value.fields && currentFieldIndex.value >= 0) {
          currentFormTemplate.value.fields[currentFieldIndex.value] = fieldData;
          currentFormTemplate.value.fields.sort((a, b) => a.sortOrder - b.sortOrder);
        }

        ElMessage.success('字段修改成功');
      } else {
        // 新增表单模式
        // 检查字段名称是否重复（排除当前编辑的字段）
        const existingField = addForm.value.fields.find((field, index) =>
          field.fieldName === fieldForm.value.fieldName && index !== currentFieldIndex.value
        );
        if (existingField) {
          ElMessage.warning('字段名称已存在，请使用其他名称');
          return;
        }

        addForm.value.fields[currentFieldIndex.value] = fieldData;
        addForm.value.fields.sort((a, b) => a.sortOrder - b.sortOrder);
        ElMessage.success('字段修改成功');
      }
    }

    handleCloseFieldDialog();
  } catch (error: any) {
    console.error('字段操作失败:', error);
    ElMessage.error(error.message || '字段操作失败');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadFormTemplateList();
});
</script>

<style lang="less" scoped>
.app-container {
  padding: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style>
